/*
 * Copyright (c) 2010 MoSync AB
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "InterpreterMoblet.h"
#include <maheap.h>
#include <conprint.h>
#include <MAInterpreter/System.h>

using namespace MAUtil;

namespace MAInterpreter
{

InterpreterMoblet::InterpreterMoblet(AbstractInterpreter* interpreter) :
	interpreter(interpreter)
{
}

InterpreterMoblet::~InterpreterMoblet()
{
	if (interpreter)
	{
		delete interpreter;
		interpreter = NULL;
	}
}

void InterpreterMoblet::keyPressEvent(int keyCode, int nativeCode)
{
	interpreter->onKeyDown(keyCode, nativeCode);
	checkIfRunningAndExitIfNot();
}

void InterpreterMoblet::keyReleaseEvent(int keyCode, int nativeCode)
{
	interpreter->onKeyUp(keyCode, nativeCode);
	checkIfRunningAndExitIfNot();
}

void InterpreterMoblet::multitouchPressEvent(MAPoint2d point, int touchId)
{
	interpreter->onTouchDown(point.x, point.y, touchId);
	checkIfRunningAndExitIfNot();
}

void InterpreterMoblet::multitouchMoveEvent(MAPoint2d point, int touchId)
{
	interpreter->onTouchDrag(point.x, point.y, touchId);
	checkIfRunningAndExitIfNot();
}

void InterpreterMoblet::multitouchReleaseEvent(MAPoint2d point, int touchId)
{
	interpreter->onTouchUp(point.x, point.y, touchId);
	checkIfRunningAndExitIfNot();
}

void InterpreterMoblet::customEvent(const MAEvent& event)
{
	MAEvent* pEvent = (MAEvent*) &event;
	interpreter->onCustomEvent(pEvent);
	checkIfRunningAndExitIfNot();
}

void InterpreterMoblet::closeEvent()
{
	interpreter->onClose();
}

void InterpreterMoblet::mainLoop()
{
	Moblet::run(this);
}

/**
 * If the interpreter wishes to end execution we exit the moblet main loop.
 */
void InterpreterMoblet::checkIfRunningAndExitIfNot()
{
	if (!interpreter->isRunning())
	{
		mRun = false;
	}
}

}

